import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '../stores'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      component: () => import('@/views/login/LoginPage.vue')
    },
    {
      path: '/layout',
      component: () => import('@/views/layout/LayoutPage.vue'),
      redirect: '/tasks',
      children: [
        {
          path: '/tasks',
          component: () => import('@/views/tasks/AddTask.vue'),
          redirect: '/tasks/today',
          children: [
            { path: '/tasks/today', component: () => import('@/views/tasks/TodayTasks.vue') },
            { path: '/tasks/sevendays', component: () => import('@/views/tasks/SevenDaysTasks.vue') },
            { path: '/tasks/all', component: () => import('@/views/tasks/AllTasks.vue') },
            { path: '/tasks/finished', component: () => import('@/views/tasks/FinishedTasks.vue') },
            { path: '/tasks/deleted', component: () => import('@/views/tasks/DeletedTasks.vue') },
            { path: '/tasks/:classifyName', component: () => import('@/views/tasks/OtherTasks.vue') },
          ]
        },
        {
          path: '/calendar',
          component: () => import('@/views/calendar/CalendarPage.vue')
        }
      ]
    }
  ],
})

// 所有的路由在真正被访问到之前（解析渲染对应组件页面之前），都会先经过全局前置守卫
// 只有全局前置守卫放行了，才会到达相应的页面
// 全局前置守卫
router.beforeEach((to, from, next) => {
  console.log('from' + from)
  console.log('to' + to)  
  // 等待 store 初始化后再进行权限验证
  const userStore = useUserStore()
  // 如果是访问登录页，直接放行
  if (to.path === '/') {
    next()
    return
  }
  // 权限页面判断是否有token
  if (!userStore.token) {
    // 没有token，重定向到登录页
    next('/')
    return
  }
  // 有token，则跳转到对应页面
  next()
})

export default router
